import {
    StyleSheet,
    Text,
    View,
    Animated,
    TouchableOpacity,
    Platform,
    Dimensions,
    Keyboard,
    ScaledSize,
    LayoutChangeEvent,
    Image,
} from 'react-native';
import React from 'react';
import { CommonActions, useTheme } from '@react-navigation/native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { px2dp } from '~/utils/px2dp';

interface Props {
    state: any;
    navigation: any;
    descriptors: any;
    activeBackgroundColor?: any;
    activeTintColor?: any;
    adaptive?: any;
    allowFontScaling?: any;
    inactiveBackgroundColor?: any;
    inactiveTintColor?: any;
    keyboardHidesTabBar?: any;
    labelPosition?: any;
    labelStyle?: any;
    safeAreaInsets?: any;
    showIcon?: any;
    showLabel?: any;
    style?: any;
    tabStyle?: any;
}

const iconSource: any = {
    Home: {
        active: require('~/assets/tabbar/ic_home_active.png'),
        inactive: require('~/assets/tabbar/ic_home_inactive.png'),
    },
    Health: {
        active: require('~/assets/tabbar/ic_menue_active.png'),
        inactive: require('~/assets/tabbar/ic_find_inactive.png'),
    },
    // Cricle: {
    //     active: require('~/assets/tabbar/ic_find_active.png'),
    //     inactive: require('~/assets/tabbar/ic_menue_inactive.png'),
    // },
    Personage: {
        active: require('~/assets/tabbar/ic_mine_active.png'),
        inactive: require('~/assets/tabbar/ic_mine_inactive.png'),
    },
};
const useNativeDriver = Platform.OS !== 'web';

export default function BottomTabBar(props: Props) {
    const {
        state,
        navigation,
        descriptors,
        activeBackgroundColor,
        activeTintColor,
        adaptive = true,
        allowFontScaling,
        inactiveBackgroundColor,
        inactiveTintColor,
        keyboardHidesTabBar = false,
        labelPosition,
        labelStyle,
        safeAreaInsets,
        showIcon,
        showLabel,
        style,
        tabStyle,
    } = props;
    const { colors } = useTheme();
    const defaultInsets = useSafeAreaInsets();
    const focusedRoute = state.routes[state.index];
    const focusedDescriptor = descriptors[focusedRoute.key];
    const focusedOptions = focusedDescriptor.options;

    const [isKeyboardShown, setIsKeyboardShown] = React.useState(false);

    const shouldShowTabBar = focusedOptions.tabBarVisible !== false && !(keyboardHidesTabBar && isKeyboardShown);

    const [isTabBarHidden, setIsTabBarHidden] = React.useState(!shouldShowTabBar);

    const [visible] = React.useState(() => new Animated.Value(1));
    React.useEffect(() => {
        if (shouldShowTabBar) {
            Animated.timing(visible, {
                toValue: 1,
                duration: 250,
                useNativeDriver,
            }).start(({ finished }) => {
                if (finished) {
                    setIsTabBarHidden(false);
                }
            });
        } else {
            setIsTabBarHidden(true);

            Animated.timing(visible, {
                toValue: 0,
                duration: 200,
                useNativeDriver,
            }).start();
        }
    }, [shouldShowTabBar, visible]);

    const [dimensions, setDimensions] = React.useState(() => {
        const { height = 0, width = 0 } = Dimensions.get('window');

        return { height, width };
    });
    React.useEffect(() => {
        const handleOrientationChange = ({ window }: { window: ScaledSize }) => {
            setDimensions(window);
        };
        Dimensions.addEventListener('change', handleOrientationChange);
        const handleKeyboardShow = () => setIsKeyboardShown(true);
        const handleKeyboardHide = () => setIsKeyboardShown(false);

        if (Platform.OS === 'ios') {
            Keyboard.addListener('keyboardWillShow', handleKeyboardShow);
            Keyboard.addListener('keyboardWillHide', handleKeyboardHide);
        } else {
            Keyboard.addListener('keyboardDidShow', handleKeyboardShow);
            Keyboard.addListener('keyboardDidHide', handleKeyboardHide);
        }

        return () => {
            if (Platform.OS === 'ios') {
                Keyboard.removeAllListeners('keyboardWillShow');
                Keyboard.removeAllListeners('keyboardWillHide');
            } else {
                Keyboard.removeAllListeners('keyboardDidShow');
                Keyboard.removeAllListeners('keyboardDidHide');
            }
        };
    }, []);

    const [layout, setLayout] = React.useState({
        height: 0,
        width: dimensions.width,
    });

    const { routes } = state;
    const handleLayout = (e: LayoutChangeEvent) => {
        const { height, width } = e.nativeEvent.layout;
        setLayout((layout) => {
            if (height === layout.height && width === layout.width) {
                return layout;
            } else {
                return {
                    height,
                    width,
                };
            }
        });
    };
    const insets = {
        top: safeAreaInsets?.top ?? defaultInsets.top,
        right: safeAreaInsets?.right ?? defaultInsets.right,
        bottom: safeAreaInsets?.bottom ?? defaultInsets.bottom,
        left: safeAreaInsets?.left ?? defaultInsets.left,
    };

    const tabBarItems = routes.map((route: any, index: number) => {
        const focused = index === state.index;
        const tabBarLabel = descriptors[route.key].options.tabBarLabel || route.name;

        const onPress = () => {
            const event = navigation.emit({
                type: 'tabPress',
                target: route.key,
                canPreventDefault: true,
            });
            if (!focused && !event.defaultPrevented) {
                navigation.dispatch({
                    ...CommonActions.navigate(route.name),
                    target: state.key,
                });
            }
        };
        const onLongPress = () => {
            navigation.emit({
                type: 'tabLongPress',
                target: route.key,
            });
        };
        return (
            <TouchableOpacity
                style={styles.tabItem}
                activeOpacity={0.9}
                key={route.key}
                onPress={onPress}
                onLongPress={onLongPress}>
                <TabBarIcon
                    name={route.name}
                    focused={focused}
                    activeTintColor={activeTintColor}
                    inactiveTintColor={inactiveTintColor}
                />
                <Text style={[styles.label, focused && { color: '#fff' }]}>{tabBarLabel}</Text>
            </TouchableOpacity>
        );
    });

    return (
        <Animated.View
            style={[
                styles.bottomTabBar,
                {
                    backgroundColor: '#08090B',
                    borderTopColor: 'rgba(255, 255, 255, 0.12)',
                },
                {
                    transform: [
                        {
                            translateY: visible.interpolate({
                                inputRange: [0, 1],
                                outputRange: [layout.height + insets.bottom, 0],
                            }),
                        },
                    ],
                },
                {
                    height: 56 + insets.bottom,
                    paddingBottom: insets.bottom * 0.9,
                    paddingHorizontal: Math.max(insets.left, insets.right),
                },
                focusedOptions.tabBarStyle,
            ]}
            pointerEvents={isTabBarHidden ? 'none' : 'auto'}>
            <View style={styles.content} onLayout={handleLayout}>
                {tabBarItems}
            </View>
        </Animated.View>
    );
}
function TabBarIcon({ name, focused, translucent, activeTintColor, inactiveTintColor }: any) {
    return (
        <View style={styles.tabBarIcon}>
            <View style={styles.icon}>
                <Image
                    resizeMode="contain"
                    source={
                        focused
                            ? iconSource[name].active
                            : translucent
                            ? iconSource[name].videoActive
                            : iconSource[name].inactive
                    }
                    style={styles.iconSize}
                />
            </View>
        </View>
    );
}

const styles = StyleSheet.create({
    bottomTabBar: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        borderTopWidth: StyleSheet.hairlineWidth,
        elevation: 8,
    },
    hidden: {
        zIndex: -2,
        opacity: 0,
    },
    tabItem: {
        flex: 1,
        position: 'relative',
        alignSelf: 'stretch',
        alignItems: 'center',
        justifyContent: 'center',
    },
    tabBarIcon: {
        position: 'relative',
        width: 24,
        height: 24,
    },
    icon: {
        position: 'absolute',
        alignSelf: 'center',
        alignItems: 'center',
        justifyContent: 'center',
        height: '100%',
        width: '100%',
        minWidth: 26,
    },
    iconSize: {
        width: px2dp(40),
        height: px2dp(40),
    },
    label: {
        fontSize: 10,
        marginTop: px2dp(4),
        color: '#a4a4a4',
    },
    content: {
        flex: 1,
        flexDirection: 'row',
        position: 'relative',
    },
});
